<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="keyWord" placeholder="试卷名称" clearable></el-input>
      </el-form-item>

      <el-form-item>
        <el-select clearable filterable v-model="query.grade_type" placeholder="请选择年级">
          <el-option
            v-for="item in gradeTypeList"
            :key="item.id"
            :label="item.value"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-if="query.grade_type"
          clearable filterable
          v-model="query.subjectId"
          placeholder="请选择科目">
          <el-option
            v-for="item in subjectList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          v-if="hasPermission(['system:testPaper:list'])"
          @click="searchPaper"
          type="primary" icon="el-icon-search">查询</el-button>
        <el-button
          icon="el-icon-circle-plus-outline"
          type="success" plain
          v-if="hasPermission(['system:testPaper:save'])"
          @click="addPaper">新增试卷</el-button>
        <el-button
          v-if="hasPermission(['system:testPaper:export'])"
          icon="el-icon-upload2"
          plain @click="exportTestPaper">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="testPaperList"
      border
      @selection-change="handleSelectionChange"
      v-loading="loading"
      style="width: 100%;">

      <el-table-column
        type="selection"
        align="center"
        width="50">
      </el-table-column>

      <el-table-column
        prop="name"
        align="center"
        min-width="140"
        :show-overflow-tooltip="true"
        label="试卷名称">
      </el-table-column>

      <el-table-column
        align="center"
        width="120"
        label="年级">
        <template slot-scope="scope">
          <el-tag size="small">{{scope.row.grade_type | getGradeName}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="mark"
        align="center"
        width="80"
        label="总分">
      </el-table-column>

      <el-table-column
        prop="subject_name"
        align="center"
        width="120"
        label="科目">
      </el-table-column>

<!--      <el-table-column
        align="center"
        width="120"
        label="类型">
        <template slot-scope="scope">
           <el-tag v-if="scope.row.type === 3" type="danger">入学测试试卷<</el-tag>
           <el-tag v-else-if="scope.row.type === 1" type="warning">错题纠正试卷<</el-tag>
           <el-tag v-else>模式试卷</el-tag>
        </template>
      </el-table-column>-->

      <el-table-column
        prop="remark"
        align="center"
        :show-overflow-tooltip="true"
        width="120"
        label="备注">
      </el-table-column>

      <el-table-column
        prop="create_date"
        align="center"
        width="180"
        :formatter="formatterCreateDate"
        label="创建时间">
      </el-table-column>

      <el-table-column
        align="center"
        min-width="250"
        label="操作">
        <template slot-scope="scope">
          <el-button
            size="small"
            v-if="hasPermission(['system:testPaper:relevanceQuestion'])"
            @click="relevanceQuestion(scope.row)"
            type="primary">试题管理</el-button>
          <el-button
            size="small"
            v-if="hasPermission(['system:testPaper:update'])"
            @click="updateTestPaperInfo(scope.row)"
            type="warning">修改</el-button>
          <el-button
            size="small"
            v-if="hasPermission(['system:testPaper:deleteById'])"
            @click="deleteById(scope.row)"
            type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <paper-question-dialog-list
       :showFlag="questionListDialog"
       @closeDialog="closeDialog"
       @close="closeForm"
       :gradeTypeList="gradeTypeList"
       :params="queryParams">
    </paper-question-dialog-list>

    <paper-form
      :showFlag="formDialog"
      @closeDialog="closeDialog"
      :formData="paperForm"
      @close="closeForm">
    </paper-form>
  </div>
</template>
<script>
  import paperForm from '@/components/education/paper-form'
  import paperQuestionDialogList from '@/components/education/paper-question-dialog-list'
  import {getGradeTypeListApi} from '@/utils/system-dict-api'
  let thisPage = null
  export default {
    name: 'testPaper',
    components: {paperForm, paperQuestionDialogList},
    data () {
      return {
        questionListDialog: false,
        testPaperList: [],
        gradeTypeList: [],
        queryParams: {
          school_type: '',
          grade_type: '',
          subject_id: ''
        },
        subjectList: [],
        query: {
          grade_type: '',
          subjectId: ''
        },
        checkedTestPaperIds: [],
        keyWord: '',
        exportLoading: null,
        formDialog: false,
        loading: false,
        currentPage: 1,
        pageSize: 10,
        questionList: [],
        totalCount: 0,
        paperForm: {
          name: '',
          grade_type: '',
          school_type: '',
          remark: '',
          subject_id: '',
          publish_flag: 0,
          sort: 0,
          exam_time: null
        }
      }
    },

    beforeCreate () {
      thisPage = this
    },

    watch: {
      'query.grade_type' (val) {
        this.getSubjectListByGradeType(val)
      }
    },

    mounted () {
      let that = this
      this.getPaperList()
      getGradeTypeListApi(data => {
        that.gradeTypeList = data
      })
    },

    methods: {

      getSubjectListByGradeType (val) {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/subject'), {
          params: {
            gradeType: val
          }
        }).then(function (response) {
          that.subjectList = response.data.data.dataList
        }).catch(function (error) {
          console.log(error)
        })
      },

      handleSizeChange (val) {
        this.currentPage = 1
        this.pageSize = val
        this.getPaperList()
      },

      handleSelectionChange (val) {
        this.checkedTestPaperIds = val
      },

      handleCurrentChange (val) {
        this.currentPage = val
        this.getPaperList()
      },

      // 点击Dialog 右上角关闭图标时触发
      closeDialog () {
        this.closeForm()
        this.getPaperList()
      },

      getGradeTypeList () {
        let that = this
        getGradeType(function (data) {
          that.gradeTypeList = data
        })
      },

      searchPaper () {
        this.currentPage = 1
        this.getPaperList()
      },

      // 试卷导出
      exportTestPaper () {
        let that = this
        if (that.checkedTestPaperIds.length === 0) {
          that.$message.error('请选择试卷导出')
          return
        }
        let ids = []
        let subjectNames = []
        that.checkedTestPaperIds.forEach(testPaperId => {
          ids.push(testPaperId.id)
          subjectNames.push(testPaperId.subject_name)
        })
        let params = {
          'testPaperIds': ids,
          'subjectNames': subjectNames
        }
        that.exportLoading = that.$loading({
          lock: true,
          text: '正在导出试卷试题,请等待。。。',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        that.axios.post(that.$http.httpUrl('/system/testPaper/export'), params).then(function (response) {
          if (response.data.code === 1) {
            that.$message({
              type: 'success',
              message: '导出成功'
            })
            that.exportLoading.close()
            setTimeout(function () {
              location.href = that.$http.getFileHost() + '/' + response.data.message
            }, 500)
          } else {
            that.$message({
              type: 'error',
              message: response.data.message
            })
          }
        })
      },

      updateTestPaperInfo (item) {
        this.formDialog = true
        this.paperForm = {
          name: item.name,
          grade_type: item.grade_type,
          school_type: item.school_type,
          remark: item.remark,
          subject_id: item.subject_id,
          publish_flag: item.publish_flag ? 1 : 0,
          sort: item.sort,
          exam_time: item.exam_time,
        }
        delete (this.paperForm.subject_name)
        // this.paperForm.entrance_flag = item.entrance_flag ? 1 : 0
      },

      // 点击Dialog 取消按钮时触发
      closeForm () {
        this.formDialog = false
        this.questionListDialog = false
        this.getPaperList()
        this.clearFormData()
      },

      deleteById (item) {
        if (item.use_flag) {
          this.$message.error('试卷' + item.name + '已被使用,无法删除')
          return
        }
        let that = this
        that.$confirm('确定删除试卷' + item.name + '?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          that.axios.delete(that.$http.httpUrl('/system/testPaper'), {
            data: item
          }).then(function (response) {
            if (response.data.code === 1) {
              that.$message({
                type: 'success',
                message: response.data.message
              })
              that.getPaperList()
            } else {
              that.$message({
                type: 'error',
                message: response.data.message
              })
            }
          })
        })
      },

      clearFormData () {
        this.paperForm = {
          name: '',
          grade_type: '',
          school_type: '',
          remark: '',
          subject_id: '',
          publish_flag: 0,
          sort: 0
        //  type: null
        }
      },
      formatterCreateDate (row) {
        if (!row.create_date) {
          return '--'
        }
        return this.moment(row.create_date).format('YYYY-MM-DD HH:mm')
      },

      relevanceQuestion (item) {
        /* this.$store.commit('map/updatePaperQuestionParams', item)
        this.$router.push({
          name: 'paperQuestionManager'
        }) */
        this.queryParams = {
          school_type: item.school_type,
          grade_type: item.grade_type,
          subject_id: item.subject_id,
          id: item.id,
          type: item.type,
          category: item.category
        }
        this.questionListDialog = true
      },

      addPaper () {
        this.formDialog = true
      },

      getPaperList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/testPaper'), {
          params: {
            currentPage: that.currentPage,
            keyWord: that.keyWord,
            gradeType: that.query.grade_type,
            subjectId: that.query.subjectId,
            offset: (that.currentPage - 1) * that.pageSize,
            limit: that.pageSize
          }
        }).then(function (response) {
          that.testPaperList = response.data.data.dataList
          that.totalCount = response.data.data.total
        }).catch(function (error) {
          console.log(error)
        })
      }
    },

    filters: {
      getGradeName (gradeType) {
        for (let i = 0; i < thisPage.gradeTypeList.length; i++) {
          if (thisPage.gradeTypeList[i].code === gradeType) {
            return thisPage.gradeTypeList[i].value
          }
        }
        return '无'
      }
    }
  }
</script>
